import { useEffect, useState } from 'react';
import { View, Text } from '@tarojs/components';
import { AtImagePicker } from 'taro-ui';
import { uploadStore } from '@/business/store/upload/upload';
import cssModule from './index.module.scss';

/**
 * @description 上传文件
 * @author Shawn
 */

interface UploadFileProps {
  count?: number;
  length?: number;
  multiple?: boolean;
  initialUrls?: string[];
  success?: (data: any) => void
}

export default function UploadFile({ count = 1, length, multiple, initialUrls, success }: UploadFileProps) {
  const [files, setFiles] = useState<{ url: string }[]>(initialUrls ? initialUrls.map(url => ({ url })) : []);

  // 上传文件变化
  const handleChange = async (
    newFiles: { url: string }[],
    operationType: 'add' | 'remove',
    index?: number,
  ) => {
    console.log('Files changed:', newFiles, operationType, index);
    if (operationType === 'add') {
      const res = await uploadStore.getState().uploadFiles(newFiles[newFiles.length - 1]);
      if (success) {
        success(res)
      }
    }
    setFiles(newFiles);
  };

  useEffect(() => {
    setFiles(initialUrls ? initialUrls.map(url => ({ url })) : [])
  }, [initialUrls])

  return (
    <View className={cssModule.container}>
      {
        count && count > 1 && <View className={cssModule.title}>
          <Text>上传附件（最多{count}张）</Text>
        </View>
      }
      <AtImagePicker
        files={files}
        length={length}
        count={count}
        multiple={multiple}
        onChange={handleChange}
        showAddBtn={files.length < count}
      />
    </View>
  );
}
